package com.github.zxhtom.excel.expose;

import com.csvreader.CsvWriter;
import com.github.zxhtom.excel.Excel;
import com.github.zxhtom.excel.constant.HeadConstant;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @package com.github.zxhtom.excel.expose
 * @Class CsvTools
 * @Description TODO
 * @Author zhangxinhua
 * @Date 19-11-7 下午2:34
 */
public class CsvTools<T> implements Excel<T> {

    @Override
    public void readData() {

    }

    @Override
    public void export(List<T> ts) {
        String parentFileName = EasyExcelTools.class.getResource("/").getPath() + "student/csv/";
        File file = new File(parentFileName);
        if (!file.exists()) {
            file.mkdirs();
        }
        String fileName = parentFileName + System.currentTimeMillis() + ".csv";
        CsvWriter writer = new CsvWriter(fileName, ',', Charset.forName("UTF-8"));
        String head[] = new String[]{HeadConstant.FIRSTNAME,HeadConstant.SECONDNAME};
        String sixHead[] = new String[]{"学号","姓名","年龄","性别","生日","身高"};
        String sixField[] = new String[]{"id","userName","age","sex","birth","height"};
        //开始写入数据
        try {
            for (String headName : head) {
                String[] header = new String[]{headName};
                writer.writeRecord(header);
            }
            writer.writeRecord(sixHead);
            //开始填充数据
            for (T item : ts) {
                Class<?> clazz = item.getClass();
                for (int i = 0; i < sixField.length; i++) {
                    try {
                        Field field = clazz.getDeclaredField(sixField[i]);
                        field.setAccessible(true);
                        Object o = field.get(item);
                        writer.write(o.toString());
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                writer.endRecord();
            }
            //结束写入
            writer.endRecord();
            writer.flush();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}
